package com.EAsystem.controller.admin;

import com.EAsystem.annotation.RequireRole;
import com.EAsystem.entity.Student;
import com.EAsystem.entity.Class;
import com.EAsystem.entity.User;
import com.EAsystem.service.StudentService;
import com.EAsystem.service.ClassService;
import com.EAsystem.service.UserService;
import com.EAsystem.service.GradeService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
@RequireRole({1}) // 只有管理员可以访问
public class StudentManagementController {

    @Autowired
    private StudentService studentService;
    
    @Autowired
    private ClassService classService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private GradeService gradeService;

    /**
     * 学生信息管理页面
     */
    @GetMapping("/student")
    public String studentPage(@RequestParam(defaultValue = "1") int page,
                             @RequestParam(defaultValue = "5") int size,
                             @RequestParam(required = false) String studentName,
                             Model model) {
        
        PageInfo<Student> pageInfo;
        
        // 根据条件查询
        if (studentName != null && !studentName.trim().isEmpty()) {
            Student searchStudent = new Student();
            User user = new User();
            user.setRealName(studentName.trim());
            searchStudent.setUser(user);
            pageInfo = studentService.findByCondition(searchStudent, page, size);
        } else {
            pageInfo = studentService.findAllByPage(page, size);
        }
        

        List<Integer> pageNumbers = new ArrayList<>();
        for (int i = 1; i <= pageInfo.getPages(); i++) {
            pageNumbers.add(i);
        }
        
        // 获取所有班级信息，用于添加/编辑学生时选择班级
        PageInfo<Class> classPageInfo = classService.findAllByPage(1, 1000);
        List<Class> classList = classPageInfo.getList();
        
        model.addAttribute("students", pageInfo.getList());
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("totalRecords", pageInfo.getTotal());
        model.addAttribute("searchStudentName", studentName);
        model.addAttribute("pageNumbers", pageNumbers);
        model.addAttribute("classList", classList); // 添加班级列表
        
        return "admin/student";
    }

    /**
     * 查看学生详情
     */
    @GetMapping("/student/view/{id}")
    @ResponseBody
    public Map<String, Object> viewStudent(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        try {
            Student student = studentService.findById(id);
            if (student != null) {
                result.put("success", true);
                result.put("student", student);
            } else {
                result.put("success", false);
                result.put("message", "学生记录不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取学生信息失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 删除学生记录
     */
    @GetMapping("/student/delete/{id}")
    public String deleteStudent(@PathVariable Integer id) {
        studentService.delete(id);
        return "redirect:/admin/student";
    }

    /**
     * 批量删除学生记录
     */
    @GetMapping("/student/batchDelete")
    public String batchDeleteStudents(@RequestParam("ids") String ids) {
        if (ids != null && !ids.isEmpty()) {
            for (String id : ids.split(",")) {
                try {
                    studentService.delete(Integer.valueOf(id));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
        return "redirect:/admin/student";
    }

    /**
     * 获取学生总学分
     */
    @GetMapping("/student/credits/{id}")
    @ResponseBody
    public Map<String, Object> getStudentCredits(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 暂时返回0，后续可以实现具体的学分计算逻辑
            Double totalCredits = 0.0;
            result.put("success", true);
            result.put("totalCredits", totalCredits);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取学分信息失败");
        }
        return result;
    }

    /**
     * 获取班级列表
     */
    @GetMapping("/student/classes")
    @ResponseBody
    public Map<String, Object> getClasses() {
        Map<String, Object> result = new HashMap<>();
        try {
            PageInfo<Class> pageInfo = classService.findAllByPage(1, 1000); // 获取所有班级
            result.put("success", true);
            result.put("classes", pageInfo.getList());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取班级列表失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 新增学生
     */
    @PostMapping("/student/add")
    @ResponseBody
    public Map<String, Object> addStudent(@RequestParam String username,
                                         @RequestParam String password,
                                         @RequestParam String realName,
                                         @RequestParam String studentNo,
                                         @RequestParam(required = false) Integer classId,
                                         @RequestParam(required = false) Integer gender,
                                         @RequestParam(required = false) String phone,
                                         @RequestParam(required = false) String email) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查用户名是否已存在
            if (userService.findByUsername(username) != null) {
                result.put("success", false);
                result.put("message", "用户名已存在");
                return result;
            }
            
            // 检查学号是否已存在
            if (studentService.findByStudentNo(studentNo) != null) {
                result.put("success", false);
                result.put("message", "学号已存在");
                return result;
            }
            
            // 创建用户账号
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setRealName(realName);
            user.setRole(3);
            user.setStatus(1);
            
            boolean userSuccess = userService.add(user);
            if (!userSuccess) {
                result.put("success", false);
                result.put("message", "创建用户账号失败");
                return result;
            }
            
            // 获取刚创建的用户ID
            User createdUser = userService.findByUsername(username);
            
            // 创建学生记录
            Student student = new Student();
            student.setUser(createdUser);
            student.setStudentNo(studentNo);
            student.setGender(gender);
            student.setPhone(phone);
            student.setEmail(email);
            
            // 设置班级信息
            if (classId != null && classId > 0) {
                Class clazz = classService.findById(classId);
                if (clazz != null) {
                    student.setClazz(clazz);
                }
            }
            
            boolean studentSuccess = studentService.add(student);
            if (studentSuccess) {
                result.put("success", true);
                result.put("message", "新增学生成功");
            } else {
                userService.delete(createdUser.getId());
                result.put("success", false);
                result.put("message", "新增学生失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "新增学生失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 编辑学生
     */
    @PostMapping("/student/edit")
    @ResponseBody
    public Map<String, Object> editStudent(@RequestParam Integer id,
                                          @RequestParam Integer userId,
                                          @RequestParam String username,
                                          @RequestParam(required = false) String password,
                                          @RequestParam String realName,
                                          @RequestParam String studentNo,
                                          @RequestParam(required = false) Integer classId,
                                          @RequestParam(required = false) Integer gender,
                                          @RequestParam(required = false) String phone,
                                          @RequestParam(required = false) String email) {
        Map<String, Object> result = new HashMap<>();
        try {
            

            
            Student student = studentService.findById(id);
            if (student == null) {
                result.put("success", false);
                result.put("message", "学生记录不存在");
                return result;
            }
            
            User user = userService.findById(userId);
            if (user == null) {
                result.put("success", false);
                result.put("message", "用户记录不存在");
                return result;
            }
            
            // 检查用户名是否被其他用户使用
            User existingUser = userService.findByUsername(username);
            
            if (existingUser != null && !existingUser.getId().equals(userId)) {
                result.put("success", false);
                result.put("message", "用户名已被其他用户使用");
                return result;
            }
            
            // 检查学号是否被其他学生使用
            Student existingStudentWithSameNo = studentService.findByStudentNo(studentNo);
            
            if (existingStudentWithSameNo != null) {
                Long studentIdLong = Long.valueOf(id);

                if (!existingStudentWithSameNo.getId().equals(studentIdLong)) {
                    result.put("success", false);
                    result.put("message", "学号已被其他学生使用");
                    return result;
                }
            }
            
            // 更新用户信息
            user.setUsername(username);
            if (password != null && !password.trim().isEmpty()) {
                user.setPassword(password);
            }
            user.setRealName(realName);
            
            boolean userSuccess = userService.update(user);
            if (!userSuccess) {
                result.put("success", false);
                result.put("message", "更新用户信息失败");
                return result;
            }
            
            // 更新学生信息
            student.setStudentNo(studentNo);
            student.setGender(gender);
            student.setPhone(phone);
            student.setEmail(email);
            
            // 更新班级信息
            if (classId != null && classId > 0) {
                Class clazz = classService.findById(classId);
                if (clazz != null) {
                    student.setClazz(clazz);
                }
            } else {
                student.setClazz(null);
            }
            
            boolean studentSuccess = studentService.update(student);
            if (studentSuccess) {
                result.put("success", true);
                result.put("message", "编辑学生成功");
            } else {
                result.put("success", false);
                result.put("message", "编辑学生失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "编辑学生失败：" + e.getMessage());
        }
        return result;
    }
} 